package com.candy.common.domain;


import cn.hutool.core.util.StrUtil;
import com.candy.common.constant.CommonConstant;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryColumn;
import com.mybatisflex.core.query.QueryOrderBy;
import com.mybatisflex.core.table.TableDef;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import java.util.Optional;

/**
 * 通用查询参数
 * @author rong xi
 * @version 1.0
 * @date 2023/09/14 18:28
 */
@Data
@Schema(name = "通用查询参数",description = "通用查询参数")
public class QueryBaseParam {

    /**
     * 排序属性
     */
    @Schema(description = "排序属性" ,defaultValue = "createTime")
    private String sortField;

    /**
     * 排序方式
     */
    @Schema(description = "排序方式 asc-正序 desc-倒序" ,defaultValue = "desc")
    private String sortType;

    /**
     * 当前页数
     */
    @Schema(description = "当前页数" ,defaultValue = "1")
    private Integer pageNum;

    /**
     * 每页条数
     */
    @Schema(description = "每页条数" ,defaultValue = "10")
    private Integer pageSize;

    @Schema(hidden = true)
    public <T> Page<T> getPage(){
        pageNum = Optional.ofNullable(pageNum).filter(s -> s >= 1).orElse(CommonConstant.ONE);
        pageSize = Optional.ofNullable(pageSize).filter(s -> s >= 1).orElse(CommonConstant.DEFAULT_PAGE_SIZE);
        return new Page<>(pageNum,pageSize);
    }



    @Schema(hidden = true)
    public <K extends TableDef> QueryOrderBy getOrderBy(K tableDef){
        sortField = StrUtil.isNotBlank(sortField)?StrUtil.toUnderlineCase(sortField):CommonConstant.DEFAULT_ORDER_COLUMN;
        sortType = StrUtil.isNotBlank(sortType)?sortType.toUpperCase(): CommonConstant.ORDER_DESC;
        return new QueryOrderBy(new QueryColumn(tableDef, sortField),sortType);
    }


    @Schema(hidden = true)
    public void preparationExport(){
        this.pageNum = CommonConstant.ONE;
        this.pageSize = CommonConstant.MAX_PAGE_SIZE;
    }

    /**
     * 获取mongodb分页参数
     *
     * @return
     */
    @Schema(hidden = true)
    public Pageable getPageable(){
        pageNum = Optional.ofNullable(pageNum).map(i->i-1).filter(s -> s >= 0).orElse(CommonConstant.ZERO);
        pageSize = Optional.ofNullable(pageSize).filter(s -> s >= 1).orElse(CommonConstant.DEFAULT_PAGE_SIZE);
        return PageRequest.of(pageNum, pageSize, getSort());
    }


    @Schema(hidden = true)
    public Sort getSort(){
        String sortBy = StrUtil.isNotBlank(sortField)?sortField:CommonConstant.DEFAULT_ORDER_FIELD;
        Sort.Direction direction = StrUtil.isNotBlank(sortType)? Sort.Direction.DESC: Sort.Direction.ASC;
        return Sort.by(direction,sortBy);
    }

}
